package cn.example.practice.service;

import cn.example.practice.model.Goods;
import cn.example.practice.model.Order;
import cn.example.practice.model.OrderItem;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;


public class CheckoutService {
    private static final Logger LOGGER = Logger.getLogger(CheckoutService.class.getName());
    private final GoodsService goodsService;

    public CheckoutService() {
        this.goodsService = new GoodsService();
    }


    /**
     * 处理结算过程，创建订单
     *
     * @param selectedIds 商品ID数组，表示用户选择的商品
     * @param quantities  商品数量映射，键为商品ID，值为该商品的数量
     * @return 返回生成的订单对象
     */
    public Order processCheckout(String[] selectedIds, Map<String, String> quantities) {

        // 根据用户选择的商品ID和数量，计算选中的商品信息
        List<Goods> selectedGoods = goodsService.calculateSelectedGoods(selectedIds, quantities);

        // 计算选中商品的总价
        float total = goodsService.calculateTotal(selectedGoods);

        // 创建订单项列表
        List<OrderItem> orderItems = new ArrayList<>();
        for (Goods goods : selectedGoods) {
            OrderItem item = new OrderItem();
            item.setGoods(goods);
            item.setQuantity(goods.getCount());
            item.setSubtotal(goods.getTotal());
            orderItems.add(item);
        }

        // 创建订单对象
        Order order = new Order();
        order.setItems(orderItems);
        order.setTotal(total);

        // 返回生成的订单对象
        return order;
    }
}
